package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.AccountDeductVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.http11.upgrade.UpgradeServletInputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Autowired
    private UserAccountMapper userAccountMapper;

    @Autowired
    private UserAccountDetailMapper userAccountDetailMapper;


    /**
     * 初始化用户账户记录
     *
     * @param userId 用户ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserAccount(Long userId) {
        //1.创建账户对象，新增账户
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userId);
        userAccount.setTotalAmount(new BigDecimal("100"));
        userAccount.setAvailableAmount(new BigDecimal("100"));
        userAccount.setTotalIncomeAmount(new BigDecimal("100"));
        userAccountMapper.insert(userAccount);
        //2.新增账户变动历史（首次注册赠送100点）
        if (userAccount.getAvailableAmount().intValue() > 0) {
            this.saveUserAccountDetail(userId, "赠送", SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT, userAccount.getAvailableAmount(), null);
        }
    }

    /**
     * 新增账户变动日志
     *
     * @param userId    用户ID
     * @param title     资金变动缘由
     * @param tradeType 交易类型
     * @param amount    变动金额
     * @param orderNo   订单编号
     */
    @Override
    public void saveUserAccountDetail(Long userId, String title, String tradeType, BigDecimal amount, String orderNo) {
        UserAccountDetail userAccountDetail = new UserAccountDetail();
        userAccountDetail.setUserId(userId);
        userAccountDetail.setTitle(title);
        userAccountDetail.setTradeType(tradeType);
        userAccountDetail.setAmount(amount);
        userAccountDetail.setOrderNo(orderNo);
        userAccountDetailMapper.insert(userAccountDetail);
    }

    /**
     * 获取当前登录用户账户可用余额
     *
     * @return
     */
    @Override
    public BigDecimal getAvailableAmount(Long userId) {
        LambdaQueryWrapper<UserAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAccount::getUserId, userId);
        UserAccount userAccount = userAccountMapper.selectOne(queryWrapper);
        if (userAccount != null) {
            return userAccount.getAvailableAmount();
        }
        return null;
    }

    /**
     * 检查及扣减账户余额；增加账户变动日志
     *
     * @param accountDeductVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkAndDeduct(AccountDeductVo accountDeductVo) {
        //1.检查及扣减余额
        int count = userAccountMapper.checkAndDeduct(accountDeductVo.getUserId(), accountDeductVo.getAmount());
        if (count == 0) {
            throw new GuiguException(400, "账户余额不足！");
        }
        //2.新增账户变动日志
        this.saveUserAccountDetail(
                accountDeductVo.getUserId(),
                accountDeductVo.getContent(),
                SystemConstant.ACCOUNT_TRADE_TYPE_MINUS,
                accountDeductVo.getAmount(),
                accountDeductVo.getOrderNo()
        );
    }


    @Autowired
    private RechargeInfoService rechargeInfoService;

    /**
     * 用户充值，支付成功后，充值业务处理
     *
     * @param orderNo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rechargePaySuccess(String orderNo) {
        //1.根据订单编号查询充值记录 判断状态：未支付才处理
        RechargeInfo rechargeInfo = rechargeInfoService.getRechargeInfo(orderNo);
        if (rechargeInfo != null && SystemConstant.ORDER_STATUS_PAID.equals(rechargeInfo.getRechargeStatus())) {
            return;
        }
        //2.新增余额
        int count = userAccountMapper.add(rechargeInfo.getUserId(), rechargeInfo.getRechargeAmount());
        if (count == 0) {
            throw new GuiguException(400, "充值异常");
        }
        //3.新增账户变动日志
        this.saveUserAccountDetail(
                rechargeInfo.getUserId(),
                "充值：" + rechargeInfo.getRechargeAmount(),
                SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT,
                rechargeInfo.getRechargeAmount(),
                orderNo
        );
        //4.修改充值记录状态：已支付
        rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_PAID);
        rechargeInfoService.updateById(rechargeInfo);
    }

    /**
     * 分页查询当前用户充值、消费记录
     *
     * @param pageInfo 分页对象
     * @param tradeType 交易类型：1201-充值 1204-消费
     * @return
     */
    @Override
    public void getUserAccountDetailPage(Page<UserAccountDetail> pageInfo, String tradeType) {
        //1.获取当前登录用户ID
        Long userId = AuthContextHolder.getUserId();
        //2.调用持久层获取充值记录
        pageInfo = userAccountMapper.getUserAccountDetailPage(pageInfo, userId, tradeType);
    }
}
